package com.fire.user.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fire.core.mode.TMitUserToken;
import com.fire.core.service.ITMitServiceDicBaseServices;
import com.fire.core.util.BlogUtil;
import com.fire.core.util.ToolUtil;
import com.fire.user.constants.ErrorCodeConstants;
import com.fire.user.constants.MobileConstants;
import com.fire.user.model.ServiceCode;
import com.fire.user.model.TMitChannel;
import com.fire.user.model.User;
import com.fire.user.util.DateUtil;
import com.fire.user.util.HttpsUtilForJK;
import com.fire.user.util.auth.AES;
import com.fire.user.util.auth.Sign;
import com.fire.user.service.IServiceCodeService;
import com.fire.user.service.ITMitChannelService;
import com.fire.user.service.IUaService;
import com.fire.user.service.IUserServiceTwo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

/**
 * @author raoyuxing
 * @date 2018/8/13 18:59
 */
@Service
public class UaServiceImpl implements IUaService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UaServiceImpl.class);

    @Autowired
    private IUserServiceTwo userService;
    @Autowired
    private IServiceCodeService serviceCodeService;
    @Autowired
    private ITMitChannelService channelService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private ITMitServiceDicBaseServices baseService;

    /**
     * 广东移动APP单点登录
     * @param map
     * @author raoyuxing
     */
    @Override
    public Object guangdongMobileSso(Map map){

        String guangdongMobileSsoUrl = baseService.getBaseByBkey("GUANGDONG_SSOURL");
        String SsoKey = baseService.getBaseByBkey("GUANGDONG_SSOKEY");
        String headerurl = baseService.getBaseByBkey("GUANGDONG_HEADERURL");

        Map resultMap =  new HashMap();

        String uaencryptsc = String.valueOf(map.get("uaencryptsc"));
        EntityWrapper<ServiceCode> scwrapper = new EntityWrapper<>();
        scwrapper.eq("uaencryptsc",uaencryptsc);
        ServiceCode serviceCode = serviceCodeService.selectOne(scwrapper);

        EntityWrapper<TMitChannel> channelWrapper = new EntityWrapper<>();
        channelWrapper.eq("channelmark",serviceCode.getChannelmark());
        TMitChannel channel = channelService.selectOne(channelWrapper);

        //配置请求参数
        String json = JSONUtils.toJSONString(setRequest(map));
//        json = Sign.SsoCoupletTest();

        JSONObject response ;
        LOGGER.info("UaServiceImpl.guangdongMobileSso ========== 广东移动统一认证  请求参数:" + json + "请求地址:" + guangdongMobileSsoUrl);
        LOGGER.debug("UaServiceImpl.guangdongMobileSso ========== 广东移动统一认证开始 " + json );

        BlogUtil.outlog(json,"","mit/user/ualogin","guangdongMobileSso","req",channel.getChannelname());
        try {
            response = HttpsUtilForJK.httpsRequest(guangdongMobileSsoUrl,"POST",json,headerurl);
        }catch (Exception e){
            LOGGER.error("UaServiceImpl.guangdongMobileSso: 广东移动统一认证失败" + e);
            resultMap.put("status", ErrorCodeConstants.USER_MOBLIE_ERROR_ERL);
            resultMap.put("turl",serviceCode.getTurl());
            resultMap.put("message","广东移动统一认证失败,返回URL,不做登陆");
            resultMap.put("tips","广东移动统一认证失败,返回URL,不做登陆");
            resultMap.put("snsapi","NO");
            return resultMap;
        }
        LOGGER.debug("UaServiceImpl.guangdongMobileSso ========== 广东移动统一认证结束 " + response );
        BlogUtil.outlog(String.valueOf(response),"","mit/user/ualogin","guangdongMobileSso","resp",channel.getChannelname());
        Map responseMap = response;
        if (ToolUtil.isNotEmpty(responseMap)){
            Map header = (Map) responseMap.get("header");
            String resultcode = String.valueOf(header.get("resultcode"));
            if (resultcode.equals(MobileConstants.MOBLIE_SSO_SUCCESS)){
                Map body = (Map) responseMap.get("body");
                User user = new User();
                user.setEmail(String.valueOf(body.get("email")));
                String scphone = String.valueOf(body.get("msisdn"));
                user.setChannelid(channel.getChannelid());
                user.setChannelname(channel.getChannelname());
                user.setResourcetype(6);
                user.setResourceid(serviceCode.getServicecode());
                user.setResourcename(serviceCode.getServicename());
                try {

                    String phone = AES.deCodeAES(scphone,SsoKey);
                    user.setPhone(phone);
                    Map loginMap = userService.loginUser(user,serviceCode.getTurl());

                    return loginMap;
                } catch (Exception e) {
                    LOGGER.error("UaServiceImpl.guangdongMobileSso: 广东移动统一认证通过，但是用户登录失败" + e);
                    resultMap.put("status",ErrorCodeConstants.USER_MOBLIE_ERROR);
                    resultMap.put("message", "用户登录失败，请联系客服人员！");
                    resultMap.put("tips", "[2069]用户登录失败，请联系客服人员！");
                    resultMap.put("snsapi","NO");
                    return resultMap;
                }
            }else {
                LOGGER.error("UaServiceImpl.guangdongMobileSso: 广东移动统一认证失败,移动侧的返回数据:" + response);
                resultMap.put("status",ErrorCodeConstants.USER_MOBLIE_ERROR_ERL);
                resultMap.put("turl",serviceCode.getTurl());
                resultMap.put("message","广东移动统一认证失败,有返回数据,返回URL,不做登陆");
                resultMap.put("tips","广东移动统一认证失败,有返回数据,返回URL,不做登陆");
                resultMap.put("snsapi","NO");
                return resultMap;
            }
        }
        resultMap.put("status",ErrorCodeConstants.USER_MOBLIE_ERROR_ERL);
        resultMap.put("turl",serviceCode.getTurl());
        resultMap.put("message","广东移动统一认证失败,返回URL,不做登陆");
        resultMap.put("tips","广东移动统一认证失败,返回URL,不做登陆");
        resultMap.put("snsapi","NO");
        return resultMap;
    }


    /**
     * 已验证通过跳转
     * @author raoyuxing
     * @param map
     */
    @Override
    public Object verifiedJump(Map map) {

        LOGGER.debug("UaServiceImpl.verifiedJump ========== 广东移动统一认证已验证通过跳转 开始" + map );

        Integer tokenOutTime = Integer.valueOf(baseService.getBaseByBkey("GUANGDONG_TOKENOUTTIME"));

        String uaencryptsc = String.valueOf(map.get("uaencryptsc"));
        EntityWrapper<ServiceCode> scwrapper = new EntityWrapper<>();
        scwrapper.eq("uaencryptsc",uaencryptsc);
        ServiceCode serviceCode = serviceCodeService.selectOne(scwrapper);

        String token = String.valueOf(map.get("token"));
        TMitUserToken userToken = (TMitUserToken) redisTemplate.opsForValue().get(token);

        Map resultMap = new HashMap();
        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("userid",Integer.valueOf(userToken.getUserid()));
        User user = userService.selectOne(userWrapper);
        Map recordMap = new HashMap();
        recordMap.put("resourceid",serviceCode.getServicecode());
        recordMap.put("TUrl",serviceCode.getTurl());
        userService.addRecordLogin(user,"login",recordMap);

        resultMap.put("turl",replaceUrl(serviceCode.getTurl()));
        resultMap.put("status", ErrorCodeConstants.SUCCESS);
        resultMap.put("message", "登录成功");
        resultMap.put("tips", "登录成功");
        resultMap.put("token", userToken.getToken());
        resultMap.put("user", user);
        resultMap.put("snsapi","NO");
        redisTemplate.expire(userToken.getUserid().toString(),tokenOutTime , TimeUnit.MINUTES);
        redisTemplate.expire(userToken.getToken(),tokenOutTime , TimeUnit.MINUTES);

        LOGGER.debug("UaServiceImpl.verifiedJump ========== 广东移动统一认证已验证通过跳转 结束" + resultMap );

        return resultMap;
    }

    protected String replaceUrl(String url){
        String newurl = "";
        String ybtUrl = baseService.getBaseByBkey("GUANGDONG_YBTURL");
        if (url.contains(ybtUrl)){
            newurl = url.replace(ybtUrl,"");
        }else {
            newurl = url;
        }
        return newurl;
    }

    /**
     * 配置广东移动接口请求的参数
     * @param map
     * @return
     */
    protected Map setRequest(Map map){

        LOGGER.debug("UaServiceImpl.setRequest ========== 配置广东移动接口请求的参数 " + map );

        String SsoKey = baseService.getBaseByBkey("GUANGDONG_SSOKEY");

        Map request = new HashMap();
        Map body = new HashMap();
        Map header = new HashMap();

        body.put("token",String.valueOf(map.get("uatoken")));
        header.put("version","1.0");
        header.put("msgid",System.currentTimeMillis());
        header.put("systemtime",DateUtil.formatDate(new Date(),"yyyyMMddHHmmssSSS"));
        header.put("id",String.valueOf(map.get("uasourceid")));
        header.put("idtype","0");
        header.put("apptype","5");
        Map<String, Object> enMap = new TreeMap<String, Object>();
        enMap.put("token",body.get("token"));
        enMap.put("version",header.get("version"));
        enMap.put("msgid",header.get("msgid"));
        enMap.put("systemtime",header.get("systemtime"));
        enMap.put("id",header.get("id"));
        enMap.put("key", SsoKey);
        enMap.put("idtype",header.get("idtype"));
        enMap.put("apptype",header.get("apptype"));
        String enStr = Sign.mapToString(enMap);
        header.put("sign",Sign.md5(enStr));

        request.put("body",body);
        request.put("header",header);

        return request;
    }
}
